import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from 'routes'
import store from 'store'
import config from 'config/config'
Vue.use(VueRouter)
//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
    return originalReplace.call(this, location).catch(err => err)
}
const router = new VueRouter({
    routes,
    mode: 'history',
    scrollBehavior() {
        return { x: 0, y: 0 }
    }
})
//自动登录请求只有在页面刷新的时候才需要执行,用一个变量来控制
let flag = true
router.beforeEach(async (to, from, next) => {
    if(flag){
        //页面不刷新,让其变为false,不刷新则flag不会变为true 就不会进这个if
        flag = false
        //自动登录, 校验token
        const code = await store.dispatch('getUserInfo')
        if(code !== 200)
            // 如果token过期自动登出
            await store.dispatch('logout')
    }
    next()
    
})
router.beforeResolve((to, from,next)=>{
    const path = config.path
    const userInfo = store.state.user.userInfo
    // console.log(userInfo.name)
    // let token = localStorage.getItem('login_token')
    // /login/123
    
    if(userInfo.name){
        next()
    }else{
        const toPath = to.path.split('/')[1]
        if(path.includes(toPath)){
            next('/login')
        }else{
            next()
        }
    }
})
// router.afterEach( (to, from,) => {
//     console.log('全局后置钩子afterEach')
// })
export default router